<template>
    <div>

      <h2>promise的基本使用</h2>
<!--      <el-button @click="promiseele" type="danger"> Promise异步函数传参</el-button>
      <el-button @click="promiseAll" type="danger"> Promise.all与promise.race</el-button>
      <el-button @click="promiseApply" type="danger"> Promise的简单应用</el-button>
      <el-button @click="promiseandajax"> Promise封装ajax</el-button>-->
      <br>
      <br>
      <br>
      <h2>promise的底层原理★★★★★</h2>
      <el-button type="danger"> Promise的底层实现</el-button>
      <br>
      <br>
      <br>
      <h2>async与await的基本使用,优势在于处理 then 链；<span style="color: red">async函数不管返回什么都是个promise对象</span></h2>
<!--      <el-button @click="asyncApply" type="danger"> async与await的应用</el-button>-->
      <el-button @click="asyandajax" type="danger"> async与await封装ajax</el-button>
    </div>
</template>

<script>

    export default {
        name: "Promise",
        data(){
          return{

          }

        },
        methods:{


          //promise的应用
          promiseApply(){



           /* async function test(){
              try{
                let n = await Promise.all([caidaxiao('大'),caidaxiao('大')])
                console.log(n)
              }catch(error){
                console.log(error)
              }
            }
            test()*/
          },




          asyandajax(){
            // 发送 AJAX 请求, 返回的结果是 Promise★ 对象
            function sendAJAX(url) {
              return new Promise((resolve, reject) => {
                const x = new XMLHttpRequest();
                x.open('GET', url);
                x.send();
                x.onreadystatechange = function () {
                  if (x.readyState === 4) {
                    if (x.status >= 200 && x.status < 300) {
                      //成功啦
                      resolve(x.response);
                    }else{
                      //如果失败
                      reject(x.status);
                    }
                  }
                }
              })
            }

         /*   promise.then 方法测试
              sendAJAX("https://api.apiopen.top/getJoke").then(value=>{
                console.log(value);
            }, reason=>{})*/

            // async 与 await 测试  axios
            async function main(){

              let result = await sendAJAX("https://api.apiopen.top/getJoke");
              let tianqi = await sendAJAX('https://www.tianqiapi.com/api/?version=v1&city=%E5%8C%97%E4%BA%AC&appid=23941491&appsecret=TXoD5e8P')

              console.log(result);
              console.log("-----------");
              // console.log(tianqi);
            }

            main();
          }


        }
    }
</script>

<style scoped>

</style>
